package com.west.imserver.handler.impl;

import imserverentity.entity.IChattable;
import imserverentity.entity.Protocol;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.west.imserver.handler.IHandler;
import com.west.imserver.sender.Sender;
import com.west.imserver.server.IMServer;



public class ShakeHandler implements IHandler{
	private String msgType;
	private ObjectOutputStream oos;
	private Map<String, Object> params;
	
	public ShakeHandler(){}
	public ShakeHandler(String msgType, Map<String, Object> params, ObjectOutputStream oos) {
		this.msgType = msgType;
		this.params = params;
		this.oos = oos;
	}

	public String getMsgType() {
		return msgType;
	}
	public void setMsgType(String msgType) {
		this.msgType = msgType;
	}

	public ObjectOutputStream getOos() {
		return oos;
	}
	public void setOos(ObjectOutputStream oos) {
		this.oos = oos;
	}
	
	
	@Override
	public void handle() throws IOException {
		IChattable from = (IChattable) params.get("from");
		String to = (String) params.get("to");		
		Map<String, Object> bParams = new HashMap<String, Object>();
		bParams.put("from", from);
		bParams.put("to", to);
		Protocol bProtocol = new Protocol(msgType, bParams);
		if("All".equals(to)) {
			Set<IChattable> set = IMServer.senders.keySet();
			for(IChattable toClient : set) {
				ObjectOutputStream ooss= IMServer.senders.get(IMServer.clients.get(toClient));
				Sender.send(bProtocol, ooss);
			}
		} else {
			IChattable client = IMServer.clients.get(to);
			ObjectOutputStream ooss = IMServer.senders.get(client);
			System.out.println("client: " + client + ", ooss: " + ooss);
			Sender.send(bProtocol, ooss);
		}
	}

}
